package com.khiker.linklist;

public class P705_HashSet {


    public P705_HashSet() {
        this.length = 256;
        this.size = 0;
        array = new ListNode[length];
    }

    private int length;
    private int size;
    ListNode[] array;

    public void add(int key) {
        int hash = hash(key);
        ListNode v = array[hash];
        if (v == null) {
            array[hash] = new ListNode(key);
        } else {
            ListNode pre;
            do {
                if (v.val == key) {
                    return;
                }
                pre = v;
                v = v.next;
            } while (v != null);
            pre.next = new ListNode(key);
        }
        size++;
    }

    public void remove(int key) {
        int hash = hash(key);
        ListNode v = array[hash];
        if (v == null) {
            return;
        }
        ListNode pre = null;
        while (v != null) {
            if (v.val == key) {
                if (pre == null) {
                    array[hash] = v.next;
                } else {
                    pre.next = v.next;
                }
                size--;
            }
            pre = v;
            v = v.next;
        }
    }

    public boolean contains(int key) {
        return get(key) != null;
    }

    public ListNode get(int key) {
        int hash = hash(key);
        ListNode v = array[hash];
        while (v != null) {
            if (v.val == key) {
                return v;
            }
            v = v.next;
        }
        return null;
    }

    private int hash(int key) {
        return key >= 0 ? key % length : (-key) % length;
    }

    public static void main(String[] args) {
        P705_HashSet myHashSet = new P705_HashSet();
        myHashSet.add(1);
    }
}
